import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { VisualMan } from './visualChat.entity';
import { VisualChatInterface } from './interfaces/visualChat.interfaces';
import OpenAI from 'openai';
import { serviceInfoLog, serviceErrorLog } from "src/common/out/logger/access.logger";

@Injectable()
export class VisualChatService {
    private openai: OpenAI;
    private defaultModel = "ep-20241203002200-7vhct";

    constructor(
        @InjectRepository(VisualMan)
        private readonly visualManRepository: Repository<VisualMan>,
    ) {
        this.openai = new OpenAI({
            baseURL: "http://oneapi.guaibill.com/v1",
            apiKey: "sk-k4kjkmSuEGKslgLBB7886e842f954cF89fB46bCb6d41C609"
        });
    }

    findVisualMan(userid: string) {
        return this.visualManRepository.findOne({ where: { userid } });
    }

    async chatWithVisualMan(visualChat: VisualChatInterface) {
        try {
            let systemPrompt = "你是英语口语教师，请用英语回答";
            
            if (visualChat.chapter) {
                systemPrompt += `，当前是${visualChat.chapter}的内容`;
            }
            
            if (visualChat.stage) {
                systemPrompt += `，学习阶段是${visualChat.stage}`;
                if (visualChat.stage.includes('初级')) {
                    systemPrompt += "，请使用简单的英语词汇和句子结构，语速放慢，多解释单词含义";
                } else if (visualChat.stage.includes('中级')) {
                    systemPrompt += "，使用中等难度的词汇和句子，加入一些常用口语表达";
                } else if (visualChat.stage.includes('高级')) {
                    systemPrompt += "，可以使用较难的词汇和复杂句式，加入地道的口语表达和俚语";
                }
            }
            
            const response = await this.openai.chat.completions.create({
                model: this.defaultModel,
                messages: [
                    { role: 'system', content: systemPrompt },
                    { role: 'user', content: visualChat.content }
                ],
                temperature: 0.7,
                max_tokens: 1000
            });

            if ('choices' in response && response.choices.length > 0) {
                const answer = response.choices[0].message.content;
                serviceInfoLog(answer);
                return { answer };
            }
            return { answer: "" };
        } catch (error) {
            serviceErrorLog("error: " + error);
            return { answer: "" };
        }
    }
}

// 定义一个格式化日期的方法
function formatCurrentDate() {
    let date = new Date();
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0');
    let day = String(date.getDate()).padStart(2, '0');
    let hours = String(date.getHours()).padStart(2, '0');
    let minutes = String(date.getMinutes()).padStart(2, '0');
    let seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
